package com.victor.controller.mobile;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.victor.entity.Advertisement;
import com.victor.entity.Answer;
import com.victor.entity.Comment;
import com.victor.entity.Fans;
import com.victor.entity.FollowQuestion;
import com.victor.entity.FollowUser;
import com.victor.entity.Question;
import com.victor.entity.User;
import com.victor.entity.YhUsers;
import com.victor.entity.tags.TagsBack;
import com.victor.service.QuestionService;
import com.victor.service.UserService;
import com.victor.utils.DateUtil;
import com.victor.utils.FileUpload;
import com.victor.utils.Msg;
import com.victor.utils.TagsUtils;

/**
 * 首页
 * 
 * @author Mr.Zhang
 *
 */
@RestController
@RequestMapping("/mobile")
public class MobileController {

	@Autowired
	private QuestionService questionService;
	@Autowired
	private UserService userService;

	// 查询问题列表(首页)
	@RequestMapping("/getHomepage_question")
	public Msg getHomepage() {

		List<Question> questions = questionService.getHomepage();
		for (Question question : questions) {
			question.setQ_user(userService.getUserByid(question.getUserid()));// 将提问人信息插入返回值中
			if (question.getAnswer() != null && question.getAnswer().size() > 0) {
				int praise_num = 0;// 点赞数
				int comment_num = 0;// 评论数

				for (Answer answer : question.getAnswer()) {
					answer.setA_user(userService.getUserByid(answer.getA_userid()));// 将回答 人信息插入返回值中
					praise_num += answer.getPraise().size();
					comment_num += answer.getComment().size();
				}
				question.setPraise_num(praise_num);
				question.setComment_num(comment_num);
			}
		}
		return Msg.success().add("questions", questions);
	}

	// 获取广告列表
	@RequestMapping("/getAdvertisements")
	public Msg getAdvertisements() {
		List<Advertisement> advertisements = questionService.getAdvertisements();
		return Msg.success().add("advertisements", advertisements);
	}

	// 通过输入内容返回标签(2个)
	@RequestMapping("/getTags")
	public Msg getTags(String title) throws Exception {
		String retAskTags = TagsUtils.httpSend(title);
		TagsBack tagback = JSONObject.parseObject(retAskTags, TagsBack.class);
		return Msg.success().add("tags", tagback.getResult().getTags());
	}

	// 模糊查询(返回提问列表 和 回答人数)
	@RequestMapping("/likeQuery")
	public Msg likeQuery(String str) {
		List<Question> questions = questionService.likeQuery(str);

		return Msg.success().add("questions", questions);
	}

	// 提问(web端已做)
	@RequestMapping("/submitQuestion")
	public Msg submitQuestion(Question question, MultipartFile q_file, HttpServletRequest request) throws Exception {
		if (question == null) {
			return Msg.fail("参数错误");
		}
		if (q_file != null) {
			String q_filepath = FileUpload.uploadFile(q_file, request);
			question.setQ_filepath(q_filepath);
		}
		boolean insResult = questionService.submitQuestion(question);

		// 获取传入标签
		if (question.getLabel_1() != null && !question.getLabel_1().equals("")) {
			questionService.addLable(question.getLabel_1());
		}
		if (question.getLabel_2() != null && !question.getLabel_2().equals("")) {
			questionService.addLable(question.getLabel_2());
		}
		if (question.getLabel_3() != null && !question.getLabel_3().equals("")) {
			questionService.addLable(question.getLabel_3());
		}
		if (question.getLabel_4() != null && !question.getLabel_4().equals("")) {
			questionService.addLable(question.getLabel_4());
		}

		return insResult ? Msg.success() : Msg.fail();
	}

	// 问题详情(web端已做) 同/question/findByid

	// 采纳答案(传回答表id,提问id)
	@RequestMapping("/adoptAnswer")
	public Msg adoptAnswer(String q_id, String a_id) {
		// 通过q_id查询该提问是否有采纳的答案
		List<Answer> answers = questionService.ifadoptAnswer(q_id);
		if (answers != null && answers.size() > 0) {
			return Msg.fail("已存在采纳的答案");
		}
		boolean updResult = questionService.adoptAnswer(a_id);
		// 通过q_id查询提问详情 通过a_id查询回答人id
		Question question = questionService.findByid(Integer.valueOf(q_id));

		Answer answer = questionService.findByidToAnswer(a_id);
		answer.getA_userid();// 回答人id
		question.getQ_reward();// 问题积分
		// 通过回答人id查询回答人积分
		User userdata = questionService.getUserByUserid(answer.getA_userid());

		User user = new User();
		user.setUserid(answer.getA_userid());
		user.setIntegral(String.valueOf(Integer.valueOf(userdata.getIntegral()) + Integer.valueOf(question.getQ_reward())));
		questionService.updatePersonalData(user);

		return updResult ? Msg.success() : Msg.fail();
	}

	// 回答提问(添加10分)
	@RequestMapping("/answerQuestion")
	public Msg answerQuestion(Answer answer, MultipartFile a_file, HttpServletRequest request) throws Exception {
		if (a_file != null) {
			String a_filepath = FileUpload.uploadFile(a_file, request);
			answer.setA_filepath(a_filepath);
		}

		boolean insResult = questionService.answerQuestion(answer);
		if (insResult) {
			// 查询回答人信息
			User answerUser = questionService.getUserByUserid(answer.getA_userid());
			answerUser.setIntegral(String.valueOf(Integer.valueOf(answerUser.getIntegral()) + 10));
			questionService.updatePersonalData(answerUser);

			return Msg.success();
		}
		return Msg.fail();
	}

	// 回答页详情(提取出问题详情的单个回答和问题标题) 同/question/findByid

	// 获取某条回答的评论列表(时间排序)
	@RequestMapping("/getCommentByAnswerId")
	public Msg getCommentByAnswerId(String a_id) {// a_id 回答表id
		List<Comment> comments = questionService.getCommentByAnswerId(a_id);
		if (comments != null && comments.size() > 0) {
			for (Comment comment : comments) {
				comment.setC_user(userService.getUserByid(comment.getC_userid()));
			}
		}
		return Msg.success().add("comments", comments);
	}

	// 发布评论(单文字)
	@RequestMapping("/releaseComment")
	public Msg releaseComment(Comment comment) {
		boolean insResult = questionService.releaseComment(comment);
		return insResult ? Msg.success() : Msg.fail();
	}

	// 用户页(查询用户信息和发布的所有提问)
	@RequestMapping("/getAllQuestionByUserid")
	public Msg getAllQuestionByUserid(String userid) {
		List<Question> questions = questionService.getAllQuestionByUserid(userid);

		YhUsers user = userService.getUserByid(userid);
		return Msg.success().add("questions", questions).add("user", user);
	}

	// 关注页
	@RequestMapping("/followPage")
	public Msg followPage(String userid) {

		// 创建返回list
		List<Question> retQuestion = new ArrayList<Question>();
		// 查询我关注的人
		List<FollowUser> followUser = questionService.getFollowUser(userid);
		for (FollowUser followUser2 : followUser) {
			// 查询每个人发的提问
			List<Question> questionByUserid = questionService.getAllQuestionByUserid(followUser2.getF_userid());
			for (Question question : questionByUserid) {
				retQuestion.add(question);
			}
		}
		// 放入一个总的list里
		// 查询我关注的问题
		List<FollowQuestion> followQuestion = questionService.getFollowQuestion(userid);
		for (FollowQuestion followQuestion2 : followQuestion) {
			Question findByid = questionService.findByid(Integer.valueOf(followQuestion2.getF_questionid()));
			// 也放入list里
			retQuestion.add(findByid);
		}

		// list时间排序
		Collections.sort(retQuestion, new Comparator<Question>() {
			public int compare(Question o1, Question o2) {
				try {
					if (DateUtil.after(o1.getQ_time(), o2.getQ_time())) {
						return 1;
					}
				} catch (ParseException e) {
					// e.printStackTrace();
				}
				if (o1.getQ_time().equals(o2.getQ_time())) {
					return 0;
				}
				return -1;
			}
		});

		return Msg.success().add("followQuestion", retQuestion);
	}

	// 待解答页(查询所有没有回答的提问)
	@RequestMapping("/getQuestionsToNoAnswers")
	public Msg getQuestionsToNoAnswers() {
		List<Question> questions = questionService.getQuestionsToNoAnswers();
		return Msg.success().add("questions", questions);
	}

	// 我的--回答(查询我回答过的提问)
	@RequestMapping("/getAnswersByMe")
	public Msg getAnswersByMe(String userid) {
		List<Question> questions = questionService.getAnswersByMe(userid);
		return Msg.success().add("questions", questions);
	}

	// 我的--提问(查询所有我的提问)
	@RequestMapping("/getQuestionByMe")
	public Msg getQuestionByMe(String userid) {

		List<Question> questions = questionService.getQuestionByMe(userid);
		return Msg.success().add("questions", questions);
	}

	// 我的--关注--问题(我关注的问题)
	@RequestMapping("/getFollowQuestion")
	public Msg getFollowQuestion(String userid) {
		List<FollowQuestion> followQuestions = questionService.getFollowQuestion(userid);
		if (followQuestions != null && followQuestions.size() > 0) {
			for (FollowQuestion followQuestion : followQuestions) {
				followQuestion.setQuestion(questionService.findByid(Integer.valueOf(followQuestion.getF_questionid())));
			}
		}
		return Msg.success().add("followQuestions", followQuestions);
	}

	// 我的--关注--用户(我关注的用户)
	@RequestMapping("/getFollowUser")
	public Msg getFollowUser(String userid) {
		List<FollowUser> followUsers = questionService.getFollowUser(userid);
		if (followUsers != null && followUsers.size() > 0) {
			for (FollowUser followUser : followUsers) {
				followUser.setF_user(userService.getUserByid(followUser.getF_userid()));
			}
		}
		return Msg.success().add("followUsers", followUsers);
	}

	// 修改个人信息
	@RequestMapping("/updatePersonalData")
	private Msg updatePersonalData(User user, MultipartFile headphotofile, HttpServletRequest request) throws Exception {
		if (headphotofile != null) {
			String headphoto = FileUpload.uploadFile(headphotofile, request);
			user.setHeadphoto(headphoto);
		}

		// 通过userid查询user表中是否存在该用户
		User userData = questionService.getUserByUserid(user.getUserid());
		if (userData == null) {
			// user表中不存在该用户 则插入
			boolean insResult = questionService.insertPersonalData(user);
			return insResult ? Msg.success() : Msg.fail();

		} else {
			boolean updResult = questionService.updatePersonalData(user);
			return updResult ? Msg.success() : Msg.fail();
		}

	}

	// 粉丝列表
	@RequestMapping("/getFansList")
	public Msg getFansList(String userid) {
		List<Fans> fanslist = questionService.getFansList(userid);
		if (fanslist != null && fanslist.size() > 0) {
			for (Fans fans : fanslist) {
				fans.setFansuser(userService.getUserByid(fans.getFansid()));// 将粉丝用户信息插入返回值中
			}
		}
		return Msg.success().add("fanslist", fanslist);
	}

}
